unit RilLmStream;

interface

uses Ril, Classes;

type
  TRilStream = class(TInterfacedObject, IStream)
  private
    FBaseStream: TStream;
    FOwned: Boolean;
  protected
    function GetPosition: Int64;
    function GetSize: LongWord;
    function Read(var Buffer; Count: LongWord): LongWord;
    function Write(const Buffer; Count: LongWord): LongWord;
    procedure LoadFromFile(AFileName: string);
    procedure SaveToFile(AFileName: string);
    procedure SetPosition(const Value: Int64);
    procedure Clear;
  public
    constructor Create(AStream: TStream; AOwned: Boolean = True);
    destructor Destroy; override;
    property BaseStream: TStream read FBaseStream;
  end;

implementation

uses
  SysUtils;

procedure TRilStream.Clear;
begin
  if FBaseStream is TMemoryStream then
    TMemoryStream(FBaseStream).Clear;
end;

constructor TRilStream.Create(AStream: TStream; AOwned: Boolean = True);
begin
  FBaseStream := AStream;
  FOwned := True;
end;

destructor TRilStream.Destroy;
begin
  try
    if FOwned then
      FreeAndNil(FBaseStream);
  except 
  end;
  inherited;
end;

function TRilStream.GetPosition: Int64;
begin
  Result := FBaseStream.Position;
end;

function TRilStream.GetSize: LongWord;
begin
  Result := FBaseStream.Size;
end;

procedure TRilStream.LoadFromFile(AFileName: string);
begin
  if FBaseStream is TMemoryStream then
    TMemoryStream(FBaseStream).LoadFromFile(AFileName);
end;

function TRilStream.Read(var Buffer; Count: LongWord): LongWord;
begin
  FBaseStream.Read(Buffer, Count);
end;

procedure TRilStream.SaveToFile(AFileName: string);
begin
  if FBaseStream is TMemoryStream then
    TMemoryStream(FBaseStream).SaveToFile(AFileName);
end;

procedure TRilStream.SetPosition(const Value: Int64);
begin
  FBaseStream.Position := Value;
end;

function TRilStream.Write(const Buffer; Count: LongWord): LongWord;
begin
  FBaseStream.Write(Buffer, Count)
end;

end.
